package cn.zcx;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * description:wait 和sleep区别
 * author:zcx
 * lenovo
 * 时间：2022.02.07.14.30
 */
public class T17 {
    Object b = new Object();
    List<String> list = new ArrayList<>();

    void work() {
        String tn=Thread.currentThread().getName();
        System.out.println(tn+"线程启动");
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        while (true) {
            synchronized (b) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                String ok = "item" + (list.size() + 1);
                System.out.println(ok);
                list.add(ok);
                if (list.size() == 5) {
                    try {
                        b.notify();//唤醒其它线程，不释放当前占用的锁
                        b.wait();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    void count() {
        synchronized (b) {
            try {
                b.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("统计提示：已经到5个元素。");
            b.notify();
        }
    }

    public static void main(String[] args) {
        var t = new T17();
        new Thread(t::work, "T1").start();
        new Thread(t::count, "T2").start();

    }
}
